#include "types.h"
#include "x86.h"
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "proc.h"
#include "kthread.h"

int
sys_fork(void)
{
  return fork();
}

int
sys_exit(void)
{
  exit();
  return 0;  // not reached
}

int
sys_wait(void)
{
  return wait();
}

int
sys_kill(void)
{
  int pid;

  if(argint(0, &pid) < 0)
    return -1;
  return kill(pid);
}

int
sys_getpid(void)
{
  return proc->pid;
}

int
sys_sbrk(void)
{
  int addr;
  int n;

  if(argint(0, &n) < 0)
    return -1;
  addr = proc->sz;
  if(growproc(n) < 0)
    return -1;
  return addr;
}

int
sys_sleep(void)
{
  int n;
  uint ticks0;
  
  if(argint(0, &n) < 0)
    return -1;
  acquire(&tickslock);
  ticks0 = ticks;
  while(ticks - ticks0 < n){
    if(proc->killed){
      release(&tickslock);
      return -1;
    }
    sleep(&ticks, &tickslock);
  }
  release(&tickslock);
  return 0;
}

// return how many clock tick interrupts have occurred
// since start.
int
sys_uptime(void)
{
  uint xticks;
  
  acquire(&tickslock);
  xticks = ticks;
  release(&tickslock);
  return xticks;
}

int
sys_kthread_create(void)
{
    void *(*start_func)();
    void * stackPtr;
    int stack_size;
    
    if ((argint(0,(int *)&start_func) == 0) & (argint(1,(int *)&stackPtr) == 0) & (argint(2,&stack_size) == 0)){
		return  kthread_create(start_func,stackPtr,stack_size);
    }
    return -1;
}
    
int
sys_kthread_id(void)
{
    return kthread_id();
}

void
sys_kthread_exit(void)
{
    kthread_exit();
}

int
sys_kthread_join(void)
{
    int tid;
    if (argint(0,&tid) < 0)
		return -1;
    return kthread_join(tid);
}

int 
sys_retrieve_process_statistics(void){
    int * totalElapsedTime;
    int * totalRunTime;
    int * totalWaitTime;
    if ((argint(0,(int *)&totalElapsedTime) == 0) & (argint(1,(int *)&totalRunTime) == 0) & (argint(2,(int *)&totalWaitTime) == 0)){
		return  retrieve_process_statistics(totalElapsedTime,totalRunTime,totalWaitTime);
    }
    return -1;
}

int
sys_kthread_mutex_alloc(void){
    return kthread_mutex_alloc();
}

int
sys_kthread_mutex_dealloc(void){
    int mtx_id;
    if (argint(0,&mtx_id) < 0)
		return -1;
    return kthread_mutex_dealloc(mtx_id);
}

int
sys_kthread_mutex_lock(void){
    int mtx_id;
    if (argint(0,&mtx_id) < 0)
		return -1;
    return kthread_mutex_lock(mtx_id);
}

int
sys_kthread_mutex_unlock(void){
    int mtx_id;
    if (argint(0,&mtx_id) < 0)
		return -1;
    return kthread_mutex_unlock(mtx_id);
}

int
sys_kthread_cond_alloc(void){
    return kthread_cond_alloc();
}

int
sys_kthread_cond_dealloc(void){
    int cv_id;
    if (argint(0,&cv_id) < 0)
		return -1;
    return kthread_cond_dealloc(cv_id);
}

int
sys_kthread_cond_wait(void){
    int cv_id;
    int mtx_id;
    if (argint(0,&cv_id) != 0 || argint(1,&mtx_id) != 0)
		return -1;
    return kthread_cond_wait(cv_id,mtx_id);
}

int
sys_kthread_cond_signal(void){
    int cv_id;
    if (argint(0,&cv_id) < 0)
		return -1;
    return kthread_cond_signal(cv_id);
}